package org.jeecgframework.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.activiti.engine.runtime.ProcessInstance;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyWorkFlowService;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyContactsEntity;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.jeecgframework.web.system.pojo.base.ZyInspectionPlanEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author xiul
 * 2016-4-1 下午6:30:43
 * Description 
 */
public class ZyProcessThread implements Callable<Map<String, Object>> {
	
	private static SystemService systemService = ApplicationContextUtil.getBean("systemService");
	private static ZyWorkFlowService zyWorkFlowService = ApplicationContextUtil.getBean("zyWorkFlowService");
	private static ZyCommonService zyCommonService = ApplicationContextUtil.getBean("zyCommonService");
	
	private int beginR;
	private int endR;
	private String[] planIdsArr;
	private TSUser user;
	private String remarks;
	
	
	public ZyProcessThread(int beginR,int endR,String[] planIdsArr,TSUser user,String remarks){
		this.beginR = beginR;
		this.endR = endR;
		this.planIdsArr = planIdsArr;
		this.user = user;
		this.remarks = remarks;
	}
	
	@Override
	public Map<String, Object> call(){
		Map<String, Object> rsMap = new HashMap<String, Object>();
		List<ZyInspectionPlanEntity> rtIps = new ArrayList<ZyInspectionPlanEntity>();
		try {
			ZyContactsEntity zyContacter = null;
			//巴可服务商主管
			String barcoServerDirector = zyCommonService.queryUserNamesByOrgCodeAndRoleCode(StaticValue.ORG_CODE_BARCO,StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
			for (int i = beginR;i <= endR;i++){
				String planId = planIdsArr[i];
				ZyInspectionPlanEntity zyIP = systemService.get(ZyInspectionPlanEntity.class, planId);
				String processInsId = "";
				if(!zyIP.getState().equals(StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED)){
					////启动流程
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put(StaticValue.P_FORM_ZY_INSPECTION_PLAN_NODE01_USER, barcoServerDirector);
					//查询巡检计划第三方负责人
					zyContacter = zyContacter != null ? zyContacter : systemService.get(ZyContactsEntity.class, zyIP.getContacter().getId());
					//设置第三方负责人
					String thirdPartyHeader = zyContacter.getTsBaseUser().getUserName();
					paramsMap.put(StaticValue.P_FORM_ZY_INSPECTION_PLAN_NODE02_USER, thirdPartyHeader);
					ProcessInstance processInstance = zyWorkFlowService.startOnlineProcess(StaticValue.P_FORM_ZY_INSPECTION_PLAN, zyIP.getId(),paramsMap);
					processInsId = processInstance.getId();
				}else{
					processInsId = zyIP.getProcesssId();
				}
				//保留流程id 到 巡检计划表
				zyIP.setProcesssId(processInsId);
				zyIP.setState(StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY);
				zyIP.setSendToTpTime(new Date());
				zyIP.setRemarks(StringUtil.isNotEmpty(zyIP.getRemarks()) ? zyIP.getRemarks() + "。" + remarks : remarks);
				//更新巡检计划状态
				systemService.saveOrUpdate(zyIP);
				
//				///并 完成 分配巡检计划 这步
//				Map<String, Object> returnMap = zyWorkFlowService.processComplete("1",processInsId,"","","");
				rtIps.add(zyIP);
//				//保存巡检计划流程记录
//				ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity();
//				zyPlanRecord.setBusId(zyIP.getId());
//				zyPlanRecord.setPlanState(zyIP.getState());
//				zyPlanRecord.setProcInsId(zyIP.getProcesssId());
//				zyPlanRecord.setRemark("巴可商务主管分配巡检任务，备注："+remarks);
//				zyPlanRecord.setTsUser(user);
//				zyPlanRecord.setTaskId(((Task)returnMap.get("task")).getId());
//				zyPlanRecord.setCreateDate(new Date());
//				zyPlanRecord.setCreateBy(user.getUserName());
//				zyPlanRecord.setCreateName(user.getRealName());
//				systemService.save(zyPlanRecord);
			}
			try{
				//发送邮件
				if(null != zyContacter && StringUtil.isNotEmpty(zyContacter.getEmail())){
					ZyEmailEntity eMail = new ZyEmailEntity();
					eMail.setEmailSubject("巴可巡检任务分派通知");
					eMail.setEmailReceiver(zyContacter.getEmail());
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("tpHeaderName", zyContacter.getName());
					paraMap.put("url", StaticValue.HTTP_HEADER);
					paraMap.put("planTaskCount", planIdsArr.length);
					SendMailUtil.sendFtlMail(eMail, "mail_barcoSendToTp.ftl", paraMap,systemService);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("[启动巡检流程] - 事务出现异常,回滚事务！");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
		}
		rsMap.put("rtIps", rtIps);
		return rsMap;
	}
	
	public String[] getPlanIdsArr() {
		return planIdsArr;
	}
	public void setPlanIdsArr(String[] planIdsArr) {
		this.planIdsArr = planIdsArr;
	}

	public TSUser getUser() {
		return user;
	}
	public void setUser(TSUser user) {
		this.user = user;
	}

	public String getRemarks() {
		return remarks;
	}
	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}

	public int getBeginR() {
		return beginR;
	}
	public void setBeginR(int beginR) {
		this.beginR = beginR;
	}

	public int getEndR() {
		return endR;
	}
	public void setEndR(int endR) {
		this.endR = endR;
	}
	
	
}
